package db;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import utils.CommonUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidDBPool {

    private static DataSource ds;

    static{
        try {
            Properties properties = CommonUtils.readPropertiesFile("druid.properties");
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean initConnection() {
        Connection connection = null;
        try {
            connection = DruidDBPool.getConn();
            if (connection != null) {
                System.out.println("MySQL数据库已连接");
                return true;
            }
        } catch (Exception e) {
            System.out.println("数据库连接失败！");
            e.printStackTrace();
        } finally {
            close(connection);
        }
        return false;
    }

    public static Connection getConn() throws Exception {
        return ds.getConnection();
    }

    public static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
